package cn.hd01.export.impl;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.hd01.export.Importer;
import cn.hd01.export.RowProccess;
import cn.hd01.export.anno.Support;

import com.google.common.io.CharStreams;

@Component
@Support({ "txt", "csv" })
public class CsvImporter implements Importer {

	@Override
	public <T> void importer(InputStream is, RowProccess<T> proccess) throws Exception {
		List<String> lines = CharStreams.readLines(new InputStreamReader(is));

		int fieldNum = StringUtils.commaDelimitedListToStringArray(lines.get(0)).length;
		for (int i = 1; i < lines.size(); i++) {
			String[] fields = new String[fieldNum];

			String[] row = StringUtils.commaDelimitedListToStringArray(lines.get(i));
			for (int j = 0; j < row.length; j++) {
				fields[j] = row[j];
			}
			proccess.process(i, fields);
		}
	}
}
